#!/user/bin/env python
# -*- coding: UTF-8 -*-
# Author: xieyuheng
# Date: 2024/2/26
"""
该文件用于 单例模式实例化驱动
"""
from common.soft_operate import *
from utils.utils_log import loggerCase
from SETUP import setup
from constant import taskId_path
import uiautomation as auto_1


class Browser(object):
    """实例化驱动"""
    driver = None
    instance = False
    flag = False

    _instance = None
    _initialized = False

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.app_name = readconfig.app_name

        if not self._instance:
            self.driver = None
            self._instance = True

        if readconfig.is_need_relaunch:
            loggerCase.info("开始杀死软件")
            close_app_kill()
            self.driver = None

        """
        暂时注释，没有用到，跳过配置文件写入

        if not os.path.exists(taskId_path) and Browser.flag == False:
            setup()
            Browser.flag = True
        modify_file_configuration()    #没有用到暂时注释
        
        """
        # modify_file_configuration()
        self.get_or_launch_driver()


    def get_or_launch_driver(self):
        #实例化驱动，并查找窗口是否存在
        self.driver = auto.WindowControl(Name=self.app_name)

        if self.driver.Exists():
            self.driver.SetActive()
            #self.driver.SetTopmost()
            return self.driver
        else:
            #窗口不存在，则启动软件
            launch_app()
            self.wait_for_window()
            self.driver.SetActive()
            self.driver.SetTopmost()
            return self.driver

    def wait_for_window(self, timeout=60, interval=0.5):
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                self.window = auto.WindowControl(searchDepth=1, Name=self.app_name)
                if self.window.Exists():
                    return
            except:
                pass
                time.sleep(interval)
                loggerCase.info(f"窗口 '{self.app_name}' 在 {timeout} 秒内未出现。")
                raise Exception(f"窗口 '{self.app_name}' 在 {timeout} 秒内未出现。")


    # def __new__(cls, *args, **kwargs):
    #     """
    #
    #     :param args:
    #     :param kwargs:
    #     :return: 返回实例
    #     """
    #     if cls.driver is None:
    #
    #         app_name = "FreeScan Trak"
    #         if readconfig.is_need_relaunch:
    #             loggerCase.info("开始杀死软件")
    #             close_app_kill()
    #             cls.driver = None
    #         if cls.driver is None:
    #             """
    #             暂时注释，没有用到，跳过配置文件写入
    #
    #             if not os.path.exists(taskId_path) and Browser.flag == False:
    #                 setup()
    #                 Browser.flag = True
    #             modify_file_configuration()    #没有用到暂时注释
    #
    #             """
    #             loggerCase.info("实例化驱动")
    #             if not auto.WindowControl(Name=app_name).Exists(maxSearchSeconds=1):
    #                 launch_app()
    #                 time.sleep(35)
    #                 #enter_pass()
    #             cls.driver = auto_1.WindowControl(Name=app_name)
    #             cls.driver.SetActive()
    #             # cls.driver.SetTopmost()
    #             # if readconfig.isNeedRelaunch:
    #             #     close_all_lanch_popFrame()
    #             # auto.uiautomation.SetGlobalSearchTimeout(1)
    #             cls.instance = object.__new__(cls)
    #     return cls.driver


if __name__ == '__main__':
    Browser()




